package com.tuu.security;
import com.tuu.configBean.RedisUtil;
import com.tuu.mapper.JwtUserMapper;
import com.tuu.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
@Service("jwtUserDetailsService")
@Slf4j
public class JwtUserDetailsService implements UserDetailsService {
    //返回userdetails这个主体信息
    @Autowired
    private JwtUserMapper jwtUserMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${jwt.pVersionName}")
    String pVersionName;
    @Value("${jwt.userVersionExpiration}")
    String userExp;
    @Override
    public UserDetails loadUserByUsername(String uid) throws UsernameNotFoundException {
        System.out.println("JwtUserDetailsService:" + uid);
        List<GrantedAuthority> authorityList  = new ArrayList<>();
        //QueryWrapper qw = new QueryWrapper();
        Set<Permission> userRoles=(Set<Permission>)redisUtil.get("uid"+uid+"auths");
        String redisUserVersion=(String)redisUtil.get("uid"+uid+"pVersion");
        String reidsRolePVersion=(String)redisUtil.get(pVersionName);
        if(userRoles==null ||redisUserVersion==null || reidsRolePVersion==null ||!redisUserVersion.equals(reidsRolePVersion) ){
            log.info(">>>>>>>>>>>从数据库取userRoles");
            userRoles= jwtUserMapper.getUserAuths(Long.parseLong(uid) );
            redisUtil.set("uid"+uid+"auths",userRoles,3600);
            redisUtil.set("uid"+uid+"pVersion",reidsRolePVersion,Long.parseLong(userExp)/1000L  );
        }
        if(userRoles!=null){
            log.info(">>>>>>>>>>>进入JwtUserDetailsService");
            userRoles.forEach((role)->authorityList.add(new SimpleGrantedAuthority(role.getName())));
            //authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
            return new SecurityUserDetails(uid,authorityList);
        }
        return new SecurityUserDetails(uid,null);
    }
}